// src/utils/permissionUtils.ts
import { computed } from 'vue';
import { useAllDataStore } from '@/stores';
import { useRouter } from 'vue-router';

// 后端模块导入
import * as fs from 'fs';
import * as path from 'path';

// 获取按钮权限 hasPermission
function usePermission(): (permission: string) => boolean {
    const Store = useAllDataStore();
    const Router = useRouter();
    console.log('Router:', Router);

    let currentPagePath: string = '';

    try {
        // 获取当前页面路径并去掉开头的 '/'
        currentPagePath = Router.currentRoute.value.path;
        currentPagePath = currentPagePath.startsWith('/') ? currentPagePath.slice(1) : currentPagePath;

        // 获取用户权限列表，并添加默认值处理
        const Permissions = Store.getPermissions() || [];

        // 获取当前页面的按钮权限
        const userPermissions = computed(() => {
            if (!Array.isArray(Permissions)) {
                console.error('Permissions is not an array:', Permissions);
                return []; // 如果 Permissions 不是数组，返回空数组
            }

            const currentMenu = Permissions.find((permissions) => permissions.index === currentPagePath);
            return Array.isArray(currentMenu?.permissions) ? currentMenu.permissions : [];
        });

        // 返回一个函数，用于检查用户是否具有某种权限
        return (permission: string): boolean => {
            try {
                return userPermissions.value.includes(permission);
            } catch (error) {
                console.error('Error while checking permission:', error);
                return false; // 如果出现错误，返回 false
            }
        };
    } catch (error) {
        console.error('Error while initializing usePermission:', error);
        return (permission: string): boolean => {
            console.error('Permission check failed due to initialization error:', permission);
            return false; // 初始化错误时，所有权限检查都返回 false
        };
    }
}

// 定义结果类型
interface PermissionResult {
    path: string;
    permission: string;
    buttonName: string;
}

export { usePermission };